--[[
 * Codigo fonte baseado no mod 'Inventory Plus' 
 * Fontes: 
     * https://gitorious.org/lpgc-minetest-mods/inventory_plus/commit/d3f3f7a0feb4e3d95c038f07d9c06a8a5574174a?format=diff
	 * https://github.com/bhull2010/minetest-mod-modmenu
	 * https://github.com/cornernote/minetest-particles
	 * https://github.com/jojoa1997/overcraft_origins/tree/master/mods
 * Developer: Lunovox Heavenfinder <rui.gravata@gmail.com>
 * License: GPLv3
]]--


-- expose api
lunomenu = {}

-- define buttons
lunomenu.buttons = {}
lunomenu.listskins = { }
lunomenu.liststringskins = ""
lunomenu.selectedskin = 0
lunomenu.selectedskinTemp = 0 --E uma selecao temporaria. So entra em vigor quando o usuário clicar em Ok. (para evitar lags de overflow)

lunomenu.doListSkin = function(pasta)
	--local pasta = minetest.get_modpath("lunoskins").."/models/"
	--skin_files = { }
	local skin_files = lunomods.readdir(pasta, "*.png", "skin_") --Deve ser obrigatorio um grep. (Ja tentei criar uma funcaosem grep, mas nao funfa por causa do comando 'ls')
	--print("#skin_files("..pasta..") = "..#skin_files)
	if #skin_files >=1 then
		--local select = lunomods.getCharValue(player:get_player_name(), "skinname")
		lunomenu.selectedskin = 1
		lunomenu.selectedskinTemp = 1
		lunomenu.listskins = { lunoskins.getSkinDefault() }
		lunomenu.liststringskins = lunoskins.getSkinDefault()
		local contskins = 1 --Pelo menos deve ter que es a skin padrao
		for i, newskin in ipairs(skin_files) do 
			--print("################################# [lunomenu.doListSkin] newskin = "..newskin)
			newskin = string.gsub(newskin, "skin_", "")
			newskin = string.gsub(newskin, ".png", "")
			--print("################################# [lunomenu.doListSkin] newskin = "..newskin)
			if newskin ~= lunoskins.getSkinDefault() then
				contskins = contskins +1
				lunomenu.liststringskins = lunomenu.liststringskins..","..newskin
				lunomenu.listskins[#lunomenu.listskins + 1] = newskin
			end
		end
	end
end

if minetest.get_modpath("lunoskins")~=nil then
	lunomenu.doListSkin(minetest.get_modpath("lunoskins").."/models/")
end

-- register_button
lunomenu.register_button = function(player,name,label)
	if player ~= nil and player:is_player() then
		local player_name = player:get_player_name()
		if lunomenu.buttons[player_name] == nil then
			lunomenu.buttons[player_name] = {}
		end
		lunomenu.buttons[player_name][name] = label
	end
end

-- set_inventory_formspec
lunomenu.set_inventory_formspec = function(player,formspec)
	if minetest.setting_getbool("creative_mode") then
		-- if creative mode is on then wait a bit
		minetest.after(0.01,function()
			player:set_inventory_formspec(formspec)
		end)
	else
		player:set_inventory_formspec(formspec)
	end
end

-- get_formspec
lunomenu.get_formspec = function(player,page)
	local formspec = "size[8,7.5]"

	if player ~= nil and player:is_player() then
		minetest.log('action',"lunomenu.get_formspec.page("..player:get_player_name()..","..page..")")

		-- craft page
		if page=="main" then
			local trash = minetest.create_detached_inventory("trash", {
				-- Allow the stack to be placed and remove it in on_put()
				-- This allows the creative inventory to restore the stack
				allow_put = function(inv, listname, index, stack, player)
					return stack:get_count()
				end,
				on_put = function(inv, listname, index, stack, player)
					inv:set_stack(listname, index, "")
				end,
			})
			trash:set_size("main", 1)
		
			formspec = formspec
			.."button[0,0;2,0.5;quests;Missoes]"
			.."list[current_player;craft;2,0;3,3;]"

			.."label[5.6,0.5;Novo]"
			.."list[current_player;craftpreview;5.5,1;1,1;]"

			.."label[7.1,0.5;Lixo]"
			.."list[detached:trash;main;7,1;1,1;]"

			.."label[0,3.0;Inventario:]"
			.."list[current_player;main;0,3.5;8,4;]"


		
			if lunomenu.buttons[player:get_player_name()]~=nil then
				-- buttons
				local x,y=0,0
				for k,v in pairs(lunomenu.buttons[player:get_player_name()]) do
					formspec = formspec .. "button["..x..","..y..";2,0.5;"..k..";"..v.."]"
					y=y+0.6
				end
			end
		elseif page=="quests" then
			--[[
				 "[transformN"

					Rotates and/or flips the image.
					N can be a number (between 0 and 7) or a transform name.
					Rotations are counter-clockwise.
					0 I identity

					1 R90 rotate by 90 degrees
					2 R180 rotate by 180 degrees
					3 R270 rotate by 270 degrees
					4 FX flip X

					5 FXR90 flip X then rotate by 90 degrees
					6 FY flip Y
					7 FYR90 flip Y then rotate by 90 degrees


					mob_humanoid_citizen.png^[transformfy
					mob_humanoid_citizen.png^[brighten
					mob_humanoid_citizen.png^[verticalframe:5:0
					mob_humanoid_citizen.png^[crack:1:0


					fonte:
					 * http://dev.minetest.net/texture
					 * https://gitorious.org/marktraceur-minetest/marktraceur-minetest/source/5c26972cddb78f3f93d5d6e0428a6b282fde4bfe:src/tile.cpp#L1417-1488

			]]--
			formspec = formspec
			.."button[0,0;2,0.5;main;Voltar]"
			--.."button[0,0;2,0.5;creative_prev;Criativo]"
			--.."label[2.5,0;Missoes de "..player:get_player_name().."]"
			.."label[3.5,0;MISSOES]"
			--.."field[2.5,1;10,2;;ERROR: "..player:get_player_name()..";]"
			--.."dropdown[0,0.9;6.3;cmbPlayer; AAAAAA, bbbbbbbb, cccccccc;2]"
			--.."textlist[4.2,3;5.8,2.3;games;" .. gamemgr.gamelist() ..		";" .. menu.last_game .. ";true]"
			--.."item_image_button[X,Y;W,H;item name;name;label]"
		
			--quest(craft_swordstone)
			if lunomods.getCharValue(name, "quest(craft_swordstone)")~=true then
				formspec = formspec .."image[0.0,0.8;0.8,0.8;default_tool_stonesword.png^[brighten]"
			else
				formspec = formspec .."image[0.0,0.8;0.8,0.8;default_tool_stonesword.png]"
			end
			formspec = formspec .."label[0.8,0.8; CRIAR 1 ESPADA DE PEDRA]"
		
			--quest(kill_thief30)
			if lunomods.getCharValue(name, "quest(kill_thief30)")~=true then
				formspec = formspec .."image[0.0,1.6;0.8,0.8;mob_humanoid_citizen.png^[brighten]"
			else
				formspec = formspec .."image[0.0,1.6;0.8,0.8;mob_humanoid_citizen.png]"
			end
			formspec = formspec .."label[0.8,1.6; MATAR 30 LADROES]"
		
		
		
		
			formspec = formspec
			--.."image[0.0,1.6;0.8,0.8;mob_humanoid_citizen.png^[brighten]".."label[0.8,1.6; MATAR 30 LADROES]"
			.."image[0.0,2.4;0.8,0.8;obj_coin.png^[brighten]".."label[0.8,2.4; CONSEGUIR 10 MINEMOEDAS]"
			.."image[0.0,3.2;0.8,0.8;obj_coin.png]".."label[0.8,3.2; CONSEGUIR 10 MINEMOEDAS]"

		
			--.."label[0,1.8;(  ) 10 MINEMOEDAS]"
			--.."label[0,2.1;(  ) PROTEGER 1 TERRENO]"
		elseif page=="skins" then
		
			formspec = formspec
			.."label[3.5,0;SKINS]"
			.."button[3.0,7;2,0.5;main;Ok]"
			--.."button[0.65,7;2,0.5;skins;Aplicar]"
			--.."button[0,0;2,0.5;creative_prev;Criativo]"
			--.."label[2.5,0;Missoes de "..player:get_player_name().."]"
		
			local sel = lunomods.getCharValue(player:get_player_name(), "skinname")
			for i, skin in ipairs(lunomenu.listskins) do 
				if lunomods.getCharValue(player:get_player_name(), "skinname") == skin then 
					lunomenu.selectedskin = i 
					lunomenu.selectedskinTemp = i 
					break
				end
			end
			if lunomenu.selectedskin==nil or lunomenu.selectedskin < 1 then lunomenu.selectedskin = 1 end
			if lunomenu.liststringskins==nil or lunomenu.liststringskins =="" then lunomenu.liststringskins = lunoskins.getSkinDefault() end
			formspec = formspec
			.."textlist[0,0.7;8,6;selskin;".. lunomenu.liststringskins ..		";" .. lunomenu.selectedskin .. ";false]"

			--print("####################### [lunomenu.get_formspec(".. player:get_player_name() ..","..page..")] lunomenu.liststringskins = "..lunomenu.liststringskins)
			--print("####################### [lunomenu.get_formspec(".. player:get_player_name() ..","..page..")] lunomenu.selectedskin = "..lunomenu.selectedskin)
		
			--[[
			skin_files = lunomods.readdir(pasta, "*.png", "mobs_humanoid_")
			--print("#skin_files("..pasta..") = "..#skin_files)
			if #skin_files >=1 then
				--local select = lunomods.getCharValue(player:get_player_name(), "skinname")
				local select = 1
				local skinlist = lunoskins.getSkinDefault()
				lunomenu.listskins = { lunoskins.getSkinDefault() }
				local contskins = 1 --Pelo menos deve ter que es a skin padrao
				for i, newskin in ipairs(skin_files) do 
					newskin = string.gsub(newskin, "mobs_humanoid_", "")
					newskin = string.gsub(newskin, ".png", "")
					if newskin ~= lunoskins.getSkinDefault() then
						contskins = contskins +1
						skinlist = skinlist..","..newskin
						lunomenu.listskins[#lunomenu.listskins + 1] = newskin
						if lunomods.getCharValue(player:get_player_name(), "skinname") == newskin then select = contskins end
					end
				end
			end
			]]--

			--.."item_image_button[X,Y;W,H;item name;name;label]"
	
		end
	end
	return formspec
end

-- register_on_joinplayer
minetest.register_on_joinplayer(function(player)
	local posRespawn = lunomods.getCharValue(player:get_player_name(), "posRespawn")
	local posRespawnAll = lunomods.getGlobalValue("posRespawnAll")
	if posRespawnAll~=nil or posRespawn~=nil then
		if minetest.check_player_privs(player:get_player_name(), {gohome=true}) then
			lunomenu.register_button(player,"gohome","Go Home")
		end
	end

	if minetest.get_modpath("lunoskins")~=nil and minetest.check_player_privs(player:get_player_name(), {changeskin=true}) then 
		lunomenu.register_button(player,"skins","Skins")
	end
	
	--lunomenu.register_button(player,"craft","Craft")
	if minetest.setting_getbool("lunomobs_quests")==true then
		lunomenu.register_button(player,"quests","Missoes")
	end
	
	if minetest.setting_getbool("creative_mode") then
		lunomenu.register_button(player,"creative_prev","Ajuda")
	end
	
	minetest.after(1,function()
		lunomenu.set_inventory_formspec(player,lunomenu.get_formspec(player,"main"))
	end)
end)

-- register_on_player_receive_fields
minetest.register_on_player_receive_fields(function(player, formname, fields)
	if player ~= nil and player:is_player() then
		if fields.main then 	-- main
			lunomenu.set_inventory_formspec(player,lunomenu.get_formspec(player,"main"))
			if minetest.get_modpath("lunoskins")~=nil and lunomenu.selectedskinTemp ~= lunomenu.selectedskin then
				lunomenu.selectedskin = lunomenu.selectedskinTemp
				local nameselskin = lunomenu.listskins[lunomenu.selectedskin] or ""
				--print("#####################[minetest.register_on_player_receive_fields("..player:get_player_name()..", "..formname..", "..dump(fields)..")] nameselskin = "..nameselskin)
				lunomods.setCharValue(player:get_player_name(), "skinname", nameselskin)
				lunoskins.doUpdateSkin(player)
			end
			--return
		elseif fields.gohome then -- gohome
			lunomods.gohome(player:get_player_name())
		elseif fields.quests then -- quests
			lunomenu.set_inventory_formspec(player, lunomenu.get_formspec(player,"quests"))
			return
		elseif fields.skins and minetest.get_modpath("lunoskins")~=nil then -- skins
			lunomenu.set_inventory_formspec(player, lunomenu.get_formspec(player,"skins"))
			return
		elseif fields.selskin and minetest.get_modpath("lunoskins")~=nil  then -- quests
			local selnum = (fields.selskin):gsub("CHG:", "")
			lunomenu.selectedskinTemp = tonumber(selnum)
			return
		end
	
	
		if fields.creative_prev or fields.creative_next then -- creative
			minetest.after(0.01,function()
				lunomenu.set_inventory_formspec(player,lunomenu.get_formspec(player,"main"))
			
				--[[
				lunomenu.set_inventory_formspec(
					player, player:get_inventory_formspec()
					.."button[5,0.0;2,0.5;main;Esconder]"
					.."button[5,0.6;2,0.5;quests;Missoes]"
				)
				]]--
				return
			end)
		end
	end
end)

-- log that we started
--minetest.log("action", "[MOD]"..minetest.get_current_modname().." -- loaded from "..minetest.get_modpath(minetest.get_current_modname()))
minetest.log("action", "["..minetest.get_current_modname():upper().."] Carregado!")
